package com.cell.api.application.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * <p>
 * 服务启动监听器
 * </p>
 *
 * @author zdy
 * @date 2021/11/6
 */
@Slf4j
@Component
public class NettyServer {

    private ServerBootstrap bootstrap;
    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workGroup;
    private Channel channel;
    @Resource
    private ServerChannelInitializer serverChannelInitializer;

    /**
     * 启动服务
     *
     * @param port 端口
     */
    public void open(int port) {
        //new 一个主线程组
        bossGroup = new NioEventLoopGroup(1);
        //new 一个工作线程组
        workGroup = new NioEventLoopGroup(200);
        bootstrap = new ServerBootstrap()
                .group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                // EchoServerHandler被标注为@Sharable，所以我们可以总是使用同样的实例
                //ServerChannelInitializer实现初始化了解码器，和handler
                .childHandler(serverChannelInitializer)
                //设置tcp缓冲区, 可连接队列大小
                .option(ChannelOption.SO_BACKLOG, 1024)
                // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        //绑定端口,异步开始接收进来的连接
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            if (future.isSuccess()) {
                log.info("服务器启动成功，开始监听端口: {}", port);
            } else {
                log.info("服务器启动失败");
            }
            channel = future.channel();
            //等待服务器套接字关闭
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        } finally {
            close();
        }
    }


    public synchronized void close() {
        // 关闭服务器连接
        try {
            if (channel != null) {
                channel.close();
            }
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }
        try {
            if (bootstrap != null) {
                //关闭主线程组
                bossGroup.shutdownGracefully();
                //关闭工作线程组
                workGroup.shutdownGracefully();
            }
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }
        log.info("服务器关闭完成");
    }
}
